package com.l024.user.filter;

import com.l024.common.utils.LogUtils;
import com.l024.config.config.utils.JwtUtil;
import com.l024.user.shiro.JwtToken;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.web.filter.AccessControlFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


/*
 * 自定义一个Filter，用来拦截所有的请求判断是否携带Token
 * isAccessAllowed()判断是否携带了有效的JwtToken
 * onAccessDenied()是没有携带JwtToken的时候进行账号密码登录，登录成功允许访问，登录失败拒绝访问
 * */
public class JwtFilter extends AccessControlFilter {
    /*
     * 1. 返回true，shiro就直接允许访问url
     * 2. 返回false，shiro才会根据onAccessDenied的方法的返回值决定是否允许访问url
     * */
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
        LogUtils.logInfo("isAccessAllowed 方法被调用");
        //这里先让它始终返回false来使用onAccessDenied()方法
        //判断是否是登录登出url
        HttpServletRequest httpServletRequest = (HttpServletRequest)request;
        String servletPath = httpServletRequest.getServletPath();
        if("/login".equalsIgnoreCase(servletPath)){
            return true;
        }
        return false;
    }

    /**
     * 返回结果为true表明登录通过
     */
    @Override
    protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
        LogUtils.logInfo("onAccessDenied 方法被调用");
        //Header中获取Authorization，值就是对应的Token
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String token = request.getHeader("Authorization");
        LogUtils.logInfo("token--->"+token);
        JwtUtil jwtUtil = new JwtUtil();
       if(jwtUtil.isVerify(token)){
           JwtToken jwtToken = new JwtToken(token);
           getSubject(servletRequest, servletResponse).login(jwtToken);
//           getSubject(servletRequest, servletResponse).checkRole("admin");
           return true;
       }else{
           onLoginFail(servletResponse);
           return false;
       }
    }

    //登录失败时默认返回 401 状态码
    private void onLoginFail(ServletResponse response) throws IOException {
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        response.setContentType("text/html;charset=UTF-8");
        httpResponse.getWriter().write("请先登录");
    }
}